<template>
	<div id="canvas-container" class="canvas-container relative" ref="container">

		<a-card class="canvas-controls" :body-style="{ padding: '3px' }">
			<toolbar />
<!--			<a-button-->
<!--				type="text"-->
<!--				shape="circle"-->
<!--				size="small"-->
<!--				@click="resetView"-->
<!--				title="重置视图"-->
<!--			>-->
<!--				<home-outlined />-->
<!--			</a-button>-->
<!--			<a-button-->
<!--				type="text"-->
<!--				shape="circle"-->
<!--				size="small"-->
<!--				:type="canvasStore.showGrid ? 'primary' : 'text'"-->
<!--				@click="toggleGrid"-->
<!--				title="切换网格"-->
<!--			>-->
<!--				<border-outlined />-->
<!--			</a-button>-->
		</a-card>

		<a-spin
			v-if="isLoading"
			class="canvas-loading"
			tip="加载中..."
		/>
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { CanvasEngine } from '@/core/canvas/CanvasEngine';
import { useCanvasStore } from '@/store/modules/canvas';
import eventBus, { Events } from '@/event-bus';
import Toolbar from "@/components/Toolbar.vue";

// 容器引用
const container = ref<HTMLElement | null>(null);
// 画布引擎实例
let canvasEngine: CanvasEngine | null = null;
// 加载状态
const isLoading = ref(false);
// 画布状态
const canvasStore = useCanvasStore();

// 重置视图
const resetView = () => {
	canvasStore.resetView();
};

// 切换网格显示
const toggleGrid = () => {
	canvasStore.toggleGrid();
};

// 初始化画布引擎
onMounted(() => {
	setTimeout(()=>{
		if (container.value) {
			// 设置容器ID
			container.value.id = 'canvas-container';
			// 创建画布引擎
			canvasEngine = new CanvasEngine('canvas-container');
			resetView()
		}
	},10)

	// 监听加载状态事件
	eventBus.on(Events.SCENE_LOADED, () => {
		isLoading.value = false;
	});

	eventBus.on(Events.SCENE_SAVED, () => {
		isLoading.value = false;
	});
});

// 清理资源
onUnmounted(() => {
	if (canvasEngine) {
		canvasEngine.destroy();
		canvasEngine = null;
	}

	// 移除事件监听
	eventBus.off(Events.SCENE_LOADED);
	eventBus.off(Events.SCENE_SAVED);
});
</script>

<style scoped>
.canvas-container {
	width: 100%;
	height: 100%;
	overflow: hidden;
	position: relative;
}

.canvas-controls {
	position: absolute;
	top: 16px;
	left: 16px;
	z-index: 10;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
	width: 40px;
	height: calc(100% - 32px);
}

.ant-card-body {
	display: flex;
	gap: 8px;
}

.canvas-loading {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(255, 255, 255, 0.7);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 20;
}
</style>
